'use strict'

require('./index.css');
require('page/common/nav/index.js');
require('page/common/header/index.js');
var templateHtml = require('./index.string');
var _mm = require('util/mm.js');
var _product = require('service/product-service');
var _cart = require('service/cart-service');

var page = {
    data : {
        productId : _mm.getUrlParam('productId') || ''
    },
    init : function(){
        this.onLoad();
        this.bindEvent();
    },
    onLoad : function(){
        //判断是否有productId
        if(!this.data.productId){
            _mm.goHome();
        }
        this.loadDetail();
    },
    bindEvent : function(){
        var _this = this;
        //图片预览
        $(document).on('mouseenter','.p-img-item',function(){
            var imgUrl = $(this).find('.p-img').attr('src');
            $('.main-img').attr('src',imgUrl);
        });
        //count的操作
        $(document).on('click','.p-count-btn',function(){
            var type = $(this).hasClass('plus') ? 'plus' : 'minus',
                $pCount = $('.p-count'),
                curCount = parseInt($pCount.val()),
                minCount = 1,
                maxCount = _this.data.detailInfo.stock || 1;
            if(type === 'plus'){
                $pCount.val(curCount < maxCount ? curCount + 1 : maxCount);
            }else{
                $pCount.val(curCount > minCount ? curCount - 1 : minCount);
            }
        });
        //加入购物车
        $(document).on('click','.cart-add',function(){
            _cart.addToCart({
                productId : _this.data.productId,
                count : $('.p-count').val()
            },function(res){
                window.location.href = './result.html?type=cart-add';
            },function(errMsg){
                _mm.errorTips(errMsg);
            });
        });
    },
    //加载商品详情信息
    loadDetail : function(){
        var _this = this,
            html = '',
            $pageWrap = $('.page-wrap');
        $pageWrap.html('<div class="loading"></div>');
        _product.getProductDetail(this.data.productId,function(res){
            _this.filter(res);
            _this.data.detailInfo = res;
            html = _mm.renderHtml(templateHtml,res);
            $pageWrap.html(html);
        },function(errMsg){
            $pageWrap.html('<p class="err-tip">此商品太淘气了！</p>')
        });
    },
    filter : function(data){
        data.subImages = data.subImages.split(',');
    }
};
$(function(){
    page.init();
});